/* 
 * Copyright Terracotta, Inc. 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at 
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 *   
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 * 
 */

package org.quartz.impl.jdbcjobstore;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.quartz.spi.ClassLoadHelper;

/**
 * <p>
 * This is a driver delegate for the CUBRID JDBC driver. For Quartz 2.x
 * </p>
 * Blob handling instructions at
 * http://www.cubrid.org/manual/831/en/Using%20BLOB|CLOB Also at
 * http://www.cubrid
 * .org/wiki_tutorials/entry/working-with-cubrid-blob-clob-data-types
 *
 * @author Timothy Anyona
 * 
 * Bladnir Modify In 2016-11-8 00:53 
 * 
 * just abandon c3p0 plz 
 * 
 */
public class CUBRIDDelegate extends StdJDBCDelegate {

	public CUBRIDDelegate(Logger log, String tablePrefix, String schedName, String instanceId, ClassLoadHelper classLoadHelper) {
		super(log, tablePrefix, schedName, instanceId, classLoadHelper);
	}

	/**
	 * <p>
	 * Create new CUBRIDDelegate instance.
	 * </p>
	 *
	 * @param log
	 *            the logger to use during execution
	 * @param tablePrefix
	 *            the prefix of all table names
	 * @param useProperties
	 *            use java.util.Properties for storage
	 */
	public CUBRIDDelegate(Logger log, String tablePrefix, String schedName, String instanceId, ClassLoadHelper classLoadHelper,
			Boolean useProperties) {
		super(log, tablePrefix, schedName, instanceId, classLoadHelper, useProperties);
	}

	/**
	 * <p>
	 * This method should be overridden by any delegate subclasses that need
	 * special handling for BLOBs. The default implementation uses standard JDBC
	 * <code>java.sql.Blob</code> operations.
	 * </p>
	 *
	 * @param rs
	 *            the result set, already queued to the correct row
	 * @param colName
	 *            the column name for the BLOB
	 * @return the deserialized Object from the ResultSet BLOB
	 * @throws ClassNotFoundException
	 *             if a class found during deserialization cannot be found
	 * @throws IOException
	 *             if deserialization causes an error
	 */
	@Override
	protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {

		Object obj = null;
		InputStream binaryInput;

		Blob blob = rs.getBlob(colName);
		byte[] bytes = blob.getBytes(1, (int) blob.length());

		if (bytes != null && bytes.length != 0) {
			binaryInput = new ByteArrayInputStream(bytes);

			ObjectInputStream in = new ObjectInputStream(binaryInput);
			try {
				obj = in.readObject();
			} finally {
				in.close();
			}
		}

		return obj;
	}

	@Override
	protected Object getJobDataFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {

		if (canUseProperties()) {
			InputStream binaryInput;

			Blob blob = rs.getBlob(colName);
			byte[] bytes = blob.getBytes(1, (int) blob.length());

			if (bytes == null || bytes.length == 0) {
				return null;
			}
			binaryInput = new ByteArrayInputStream(bytes);
			return binaryInput;
		}

		return getObjectFromBlob(rs, colName);
	}

	/**
	 * Sets the designated parameter to the byte array of the given
	 * <code>ByteArrayOutputStream</code>. Will set parameter value to null if
	 * the <code>ByteArrayOutputStream</code> is null. This just wraps
	 * <code>{@link PreparedStatement#setBytes(int, byte[])}</code> by default,
	 * but it can be overloaded by subclass delegates for databases that don't
	 * explicitly support storing bytes in this way.
	 */
	@Override
	protected void setBytes(PreparedStatement ps, int index, ByteArrayOutputStream baos) throws SQLException {

		byte[] byteArray;
		if (baos == null) {
			byteArray = new byte[0];
		} else {
			byteArray = baos.toByteArray();
		}

		Connection conn = ps.getConnection();

		try {
			// will call createBlob method on the underlying connection
			Method m = conn.getClass().getMethod("createBlob");
			Blob blob = (Blob) m.invoke(conn);
			blob.setBytes(1, byteArray);
			ps.setBlob(index, blob);
		} catch (InvocationTargetException ex) {
			ex.printStackTrace();
		} catch (NoSuchMethodException ex) {
			ex.printStackTrace();
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		}

	}
}
